package com.lonely.fx;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 * @date: 2022-07-08 16:42
 * @author: ztkj-hzb
 * @description: 单选框设置
 **/
public class RadioButtonSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {


        HBox hBox = new HBox();
        hBox.setPadding(new Insets(100));
        hBox.setSpacing(30);

        Label label = new Label("选择球类：");

        //RadioButton 需要配合 ToggleGroup 使用
        ToggleGroup toggleGroup = new ToggleGroup();
        RadioButton radioBtn1 = new RadioButton("篮球");
        RadioButton radioBtn2 = new RadioButton("足球");
        RadioButton radioBtn3 = new RadioButton("羽毛球");
        radioBtn1.setToggleGroup(toggleGroup);
        radioBtn2.setToggleGroup(toggleGroup);
        radioBtn3.setToggleGroup(toggleGroup);


        //设置默认选择
        radioBtn1.setSelected(true);

        //获取当前组中被选中的RadioButton
        //RadioButton selectedToggle = (RadioButton) toggleGroup.getSelectedToggle();
        //System.out.println("被选中的Radio：" + selectedToggle.getText());

        //RadioButton 选择事件
        radioBtn1.setOnAction(event -> {
            RadioButton radioButton = (RadioButton) event.getSource();
            System.out.println(radioButton.getText() + "被选中");
        });

        //动态设置某个Radio选中
        toggleGroup.selectToggle(radioBtn3);

        //Toggle选择事件
        toggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> System.out.println(((RadioButton) newValue).getText() + "被选中"));


        hBox.getChildren().addAll(label, radioBtn1, radioBtn2, radioBtn3);

        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();

    }
}
